<template>
  <div class="progress-details">
    <div class="search">
      <div class="titles">
        <span class="title">具体招聘需求:</span>
        <span>{{currentDate?.startTime}}—{{ currentDate?.endTime }}</span>
      </div>
      <div class="search-r">
        <a-select show-search style="width: 200px" @change="searchKeyWords" v-model:value="keyWords" placeholder="请选择年份">
          <a-select-option :value="item.value" v-for="item in yearOption" :key="item.timeLabel" :code="item">{{ item.timeLabel }}</a-select-option>
        </a-select>
        <div class="tabs">
          <div class="tab-item" @click="tabChange(item.value)" v-for="item in tabsOptions" :class="{'active': actives === item.value}">{{ item.label }}</div>
        </div>
      </div>
    </div>
    <div class="top-list-view">
      <img class="img-bg" src="@/assets/images/dataCentre/recruitmentProgress/Group-349.png" alt="">
      <ul class="top-list">
        <span class="top-li-t3">合计</span>
        <li class="top-li" v-for="(item,index) in jobPostingField" :key="index">
          <span class="top-li-t1">{{ item.title }}({{item.unit}})</span>
          <span class="top-li-t2" v-if="listData">{{ listData[item.field] || 0 }}</span>
        </li>
      </ul>
    </div>
    <div class="main-content">
      <div class="bottom_table">
        <div class="result-wrap">
          <div>
            <div class="inner" v-show="resultList.length > 0">
                <span v-for="item in resultList" class="result-item">
                  {{ item.value }}
                  <CloseOutlined @click="remove(item)" />
                </span>
              <span @click="removeAll" class="result-clear">清空条件</span>
            </div>
          </div>
          <div class="modify-record" @click="openRecordDrawer">
            <img class="record-icon" src="@/assets/images/dataCentre/UniversityData/record.png" alt="">
            <span class="record-text">修改记录</span>
          </div>
        </div>
        <template v-if="parameLoading">
          <BasicTable ref="tableRef" rowKey="id" @register="registerTable" size="small" :sortFn="sortTable">
            <template #bodyCell="{ column, record }">
              <template v-if="column.key === 'edit'">
                <a-button type="primary" v-auth="'demandEdit'" @click="editData(record)" :disabled="record.subject==='待定'||record.grade==='待定年级'">编辑</a-button>
              </template>
            </template>
            <template #customFilterDropdown="{ setSelectedKeys, selectedKeys, confirm, visible, clearFilters, column }">
              <div style="padding: 8px;min-width: 270px;" v-if="Object.keys(state).length > 0">
                <div class="filter-dropdown" v-if="state[column.key]">
                  <div v-if="column.formType === 'input'">
                    <a-input v-model:value="state[column.key].inputValue" :placeholder="state[column.key].placeholder">
                      <template #prefix>
                        <SearchOutlined />
                      </template>
                    </a-input>
                  </div>
                  <div style="margin-bottom: 2px" v-else-if="column.formType === 'select'">
                    <div class="reset-top">
                      <a-input :style="{width: column.otherFormType === 'sort' ? '' : '100%'}" v-if="column.otherFormType === 'search' || column.otherFormType === 'sort'" class="reset-input" ref="searchInput" :placeholder="`搜索 ${column.title}`" :value="state[column.key].searchText" @change="handleInputChange($event, column)">
                        <template #prefix>
                          <SearchOutlined />
                        </template>
                      </a-input>
                    </div>
                    <div>
                      <Checkbox style="margin-bottom: 8px;" v-model:checked="state[column.key].checkAll" :indeterminate="state[column.key].indeterminate" @change="onCheckAllChange(column)">
                        全选
                      </Checkbox>
                      <div style="" v-if="state[column.key].options.length > 0">
                        <CheckboxGroup class='boxGroup' v-model:value="state[column.key].checkedList" :options="state[column.key].options" @change="onCheckChange(column)" />
                      </div>
                    </div>
                  </div>
                </div>
                <div style="display: flex;justify-content: space-between;margin-top: 10px;">
                  <a-button type="text" style="color: #209EE4" size="small" @click="handleReset(column)">
                    清除所选内容
                  </a-button>
                  <a-button type="primary" size="small" @click="handleSearch(selectedKeys, confirm, column)">
                    确定
                  </a-button>
                </div>
              </div>
            </template>
          </BasicTable>
        </template>
      </div>
    </div>
    <DemandEditModal ref="modal" @finishEditing="finishEditing"/>
    <RecordDrawer ref="recordDrawer" dataType="APPLICATION_TYPE"/>
  </div>
</template>

<script lang="ts" setup>
import DemandEditModal from './components/DemandEditModal.vue';
import RecordDrawer from '../UniversityData/components/RecordDrawer.vue'
import {onMounted, ref} from "vue";
import { Checkbox, CheckboxGroup, message } from 'ant-design-vue';
import { yearList } from '@/api/applay/HRData/index'
import { recruitProcessPage,recruitProcessTotal } from "@/api/data-center/recruitment-progress.ts";
import {useTable} from "@/components/Table";
import { commonColumns,selectOptions } from "./components/data/DemandDetailsData.ts"
import getSelectApi from "@/api/applay/applicationList/self.ts";

onMounted(()=>{
  getYearList()
})

// 编辑弹窗组件绑定ref
const modal = ref()

// 表格加载状态（可用于初始化表格）
const parameLoading = ref(false)

// 表格的数据
const tableData = ref([]);

// 定义一个全局请求的参数 最终进行参数组装
const requestPageData = ref(); // 是表格自带的分页请求参数信息
const diyRequestData = ref({}); // 是自定义的请求参数

// 招聘信息字段对象
const jobPostingField = ref([
  {
    title:"暑招生目标",
    field:"summerEnrollment",
    unit:"人",
  },
  {
    title:"开班数",
    field:"openedClassesNum",
    unit:"个",
  },
  {
    title:"老师总数",
    field:"allTeachersNum",
    unit:"人",
  },
  {
    title:"现有老师",
    field:"teachersNum",
    unit:"人",
  },
  {
    title:"招聘需求",
    field:"recruitNum",
    unit:"人",
  }
])

// 下拉框筛选结果集
const resultList = ref([]);

// Reload状态
const pageReloadStatus = ref(false)

// 日期选择器数据
const yearOption = ref([])
const currentDate = ref({})
const keyWords = ref(undefined)

// 表头配置
const tableColumns = ref()
tableColumns.value = commonColumns

// 编辑记录弹窗组件ref
const recordDrawer = ref()

/**
 * 输入框改变时
 * @param event
 * @param column
 */
const handleInputChange = (event, column) => {
  let searchText = event.target.value;
  state.value[column.key].options = fuzzySearch(column, searchText);
};

/**
 * 通过Columns 获取state的options
 * @param column
 * @param searchTerm
 */
function fuzzySearch(column, searchTerm: string = '') {
  // 将搜索词转换为小写，以便进行不区分大小写的比较
  const array = state.value[column.key].cacheOptions
  const lowerSearchTerm = searchTerm.toLowerCase();

  // 使用 filter 方法返回与搜索词匹配的项
  return array.filter(item => {
    // 将 label 转换为小写，并检查是否包含搜索词
    return item.label.toLowerCase().includes(lowerSearchTerm);
  });
}

/**
 * 筛选多选按钮触发
 * @param columns
 */
const onCheckChange = (columns) =>{
  if(state.value[columns.key].checkedList.length && (state.value[columns.key].checkedList.length === state.value[columns.key].options.length)){
    state.value[columns.key].checkAll = true
  } else {
    state.value[columns.key].checkAll = false
  }
}

/**
 * 筛选框全选的时候获取参数
 * @param column
 */
const onCheckAllChange = (column) => {
  state.value[column.key].indeterminate = false;
  if (state.value[column.key].checkAll) {
    const options = state.value[column.key].options;
    state.value[column.key].checkedList = options.map((el) => el.value);
  } else {
    state.value[column.key].checkedList = [];
  }
};

/**
 * 打开编辑记录弹窗
 */
const openRecordDrawer = ()=>{
  recordDrawer.value.open()
}

/**
 * 完成编辑事件
 */
const finishEditing = ()=>{
  getListData()
  reload();
}

/**
 * 编辑按钮点击事件
 * @param record
 */
const editData = (record)=>{
  const params = {
    record:record,
    schoolConfirms:state.value.schoolConfirms.options,
  }
  modal.value.open(params)
}

/**
 * 下拉筛选清除所选内容
 * @param column
 */
const handleReset = (column) => {
  if(column.formType === 'select'){
    state.value[column.key].checkAll = false;
    state.value[column.key].indeterminate = false;
    state.value[column.key].checkedList = [];
  }else if (column.formType === 'input'){
    state.value[column.key].inputValue = ''
  } else {
    state.value[column.key].timeRange = []
  }
};


/**
 * 下拉框点击确定事件
 * @param selectedKeys
 * @param confirm
 * @param column
 */
const handleSearch = (selectedKeys, confirm, column) => {
  // 表头下拉框确认事件
  confirm();
  // 通过全局缓存表头表单数据进行结果查询 并且展示出已选结果
  getResult(column);
  // 更新表格数据
  reload(gerRequestParames());
};

/**
 * 获取筛选
 * @param column
 */
const getResult = (column) => {
  const current = state.value[column.key];
  const checkedList = current.checkedList;
  if(column.formType === 'select'){
    state.value[column.key].requestValueList = checkedList
  } else if(column.formType === 'input'){
    state.value[column.key].requestValue = current.inputValue
  }
  const options = current.options;
  let result: any = [];
  if (checkedList?.length > 0) {
    options.forEach((el: any) => {
      checkedList.forEach((item) => {
        if (el.value === item) {
          result.push(el.label);
        }
      });
    });
  }
  let isExistedRow = resultList.value.find((el) => el.key == column.key);
  if (checkedList?.length === 0 && isExistedRow) {
    resultList.value = resultList.value.filter((el) => el.key != column.key);
    return;
  }
  const resStr = column.formType === 'select' ? (result.length > 3 ? result?.slice(0, 3).join('、') + ' 等' : result.join('、')) :
      column.formType === 'input' ?  current.inputValue: current.timeRange.join('-')
  const finalMap = {
    label: column.title,
    key: column.key,
    value: `${column.title}：${resStr}`,
  };
  if (isExistedRow) {
    isExistedRow.value = finalMap.value;
  } else if(!isExistedRow && resStr) {
    resultList.value.push(finalMap);
  }
};

/**
 * 初始化获取下拉框数据
 * @param item
 */
const getOptions = async (item: any) => {
  let temp = {}
  if (item.requestApi === 'selectUserByRole') {
    temp = {
      request: item.requestType,
      type: 0
    }
  }else if (item.requestApi === 'selectCommonConfig') {
    temp = {
      type: 1,
      level: item.requestType
    }
  }
  const data = await getSelectApi[item.requestApi](temp);
  const list = data.data.map((el) => {
    return {
      label: el.label || el,
      value: item.requestType==="ALL"?el.label:el.value || el,
    };
  });
  return unique(list, item.requestType)
}

/**
 * 过滤表格数据
 * @param arr
 * @param requestType
 */
function unique(arr, requestType) {
  const res = new Map();
  let list = arr.filter((a) => !res.has(a.label) && res.set(a.label, 1))
  if (requestType == '2') {
    list = list.filter(el => el.label != '小低' && el.label != '小高')
  }
  return list
}

// 表格下拉筛选的数据
const selectOptionsList = ref()
selectOptionsList.value = selectOptions
// 遍历下拉框的配置化 并且给下拉框下拉数据进行接口赋值
Object.keys(selectOptionsList.value).forEach(async (key) => {
  if (selectOptionsList.value[key]?.requestApi) {
    selectOptionsList.value[key].option = await getOptions(selectOptionsList.value[key])
  }
})

/**
 * 表格排序事件
 * @param el
 */
const sortTable = (el) => {
  delete diyRequestData.value.sortingFields
  if(el.column){
    diyRequestData.value = {
      sortingFields: [{
        field:el.column.customTitle,
        order:el.order==="ascend"?"asc":"desc"
      }],
      ...diyRequestData.value
    }
  }else{
    diyRequestData.value = {
      sortingFields: [],
      ...diyRequestData.value
    }
  }
}

/**
 * 获取日期相关信息
 */
const getYearList = async () => {
  const data = await yearList()
  if(data){
    yearOption.value = data.timeRangeList
    currentDate.value = data.currentYear
    keyWords.value = data.currentYear.timeLabel
    getListData()
    diyRequestData.value = {
      year: data.currentYear.timeLabel,
      beginTime: data.currentYear.startTime,
      endTime: data.currentYear.endTime,
      ...diyRequestData.value
    }
    parameLoading.value = true
  } else{
    message.error(data.msg)
  }
}

/**
 * 日期输入框搜索
 * @param e
 * @param option
 */
const searchKeyWords = (e,option) => {
  // 通过自定义请求参数进行接口请求
  delete diyRequestData.value.year
  delete diyRequestData.value.beginTime
  delete diyRequestData.value.endTime
  currentDate.value = option.code
  if(e){
    diyRequestData.value = {
      year: e,
      beginTime: option.code.startTime,
      endTime: option.code.endTime,
      ...diyRequestData.value
    }
  }
  reload();
}

/**
 * 筛选标签页清空所有的参数
 */
const removeAll = () => {
  resultList.value.forEach((item) => {
    state.value[item.key].checkedList = [];
    state.value[item.key].indeterminate = false;
    state.value[item.key].checkAll = false;
    state.value[item.key].indeterminate = false;
    state.value[item.key].checkedList = [];
    state.value[item.key].inputValue = '';
    state.value[item.key].timeRange = [];
    state.value[item.key].requestValueList = [];
    state.value[item.key].requestValue = '';
  });
  resultList.value = [];
  keyWords.value = currentDate.value.timeLabel
  // 更新表格数据
  reload(gerRequestParames());
};

// 筛选全局状态
const state = ref<any>({});

/**
 * 删除已选的筛选结果
 * @param item
 */
const remove = (item) => {
  if(state.value[item.key].formType === 'input') {
    state.value[item.key].requestValue = '';
    state.value[item.key].inputValue = '';
  }else {
    state.value[item.key].checkedList = [];
  }
  state.value[item.key].indeterminate = false;
  resultList.value = resultList.value.filter((v) => v.key !== item.key);
  reload()
};

/**
 * 请求表格数据
 * @param parames
 */
const getTabulationPage = (parames: any) => {
  if (parames.order && (parames.order === 'ascend' || parames.order === 'descend')) {
    return tableData.value
  }
  console.log('parames.pageSize',parames.pageSize)
  requestPageData.value = parames;
  return recruitProcessPage(gerRequestParames())
}

/**
 * 从表头下拉中获取数据
 */
const getTableHeaderRequest = () => {
  const obj = {}
  Object.keys(state.value).forEach((i: any) => {
    if (state.value[i].formType === 'select' && state.value[i].checkedList && state.value[i].checkedList.length > 0) {
      // 如果是下拉框的话
      obj[i] = state.value[i].checkedList
    } else if (state.value[i].formType === 'input' && state.value[i].inputValue) {
      // 如果是输入框的话
      obj[i] = state.value[i].inputValue
    }
  })
  return obj
}

/**
 * 请求表格参数
 */
const gerRequestParames = () => {
  const req: any = {
    ...diyRequestData.value, // 自定义请求
    ...getTableHeaderRequest(), // 表头筛选
    ...requestPageData.value, // 基础请求
  }
  return req
}


/**
 * 设置表头的下拉数据 主要用于v-modal
 */
const setTableHeader = ()=> {
  for (let i = 0; i < tableColumns.value.length; i++) {
    state.value[tableColumns.value[i].key] = {}
    state.value[tableColumns.value[i].key].formType = tableColumns.value[i].formType
    if (tableColumns.value[i].formType === 'select') {
      state.value[tableColumns.value[i].key].options = selectOptionsList.value[tableColumns.value[i].key] ? selectOptionsList.value[tableColumns.value[i].key].option : []
      state.value[tableColumns.value[i].key].cacheOptions = selectOptionsList.value[tableColumns.value[i].key] ? selectOptionsList.value[tableColumns.value[i].key].option : []
      if(tableColumns.value[i]?.field){
        selectOptionsList.value[tableColumns.value[i].key].field = tableColumns.value[i].field
      }
    } else if (tableColumns.value[i].formType === 'input') {
      state.value[tableColumns.value[i].key].inputValue = ''
    }
    state.value[tableColumns.value[i].key].placeholder = selectOptionsList.value[tableColumns.value[i].key] ? selectOptionsList.value[tableColumns.value[i].key].placeholder : ''
  }
}

// 表格配置
const tableParams = ref({
  title: '',
  api: getTabulationPage,
  columns: tableColumns.value,
  resizeHeightOffset: 10,
  formConfig: {
    labelWidth: 120,
    autoSubmitOnEnter: true,
    showAdvancedButton: true,
    autoAdvancedLine: 4,
    showSubmitButton: false,
  },
  pagination: {
    pageSize:15,
    defaultPageSize: 15,
    pageSizeOptions: ['10', '15', '20', '50'],
  },
  clearSelectOnPageChange:true,
  clickToRowSelect: false,
  useSearchForm: false,
  showTableSetting: false,
  showIndexColumn: false,
  bordered: true,
  canResize: true,
  beforeFetch(info) {
    console.log('beforeFetch----------',info)
  },
  afterFetch(list){
    // 表格请求完成后的一些处理
    // 缓存一份表格结果
    tableData.value = list
    if (!pageReloadStatus.value) {
      pageReloadStatus.value = true
      // 设置表头信息
      setTableHeader()
    }
  }
})

// 初始化表格配置
const [registerTable, { reload, setPagination, getSelectRows, setSelectedRowKeys, clearSelectedRowKeys }] = useTable(tableParams.value);

// 顶部招聘列表数据
const listData = ref(null);

/**
 * 获取招聘进度数据
 */
const getListData = async () => {
  const reqJson = {
    "country": '',
    "province": '',
    "area": '',
    "year":currentDate.value.timeLabel,
    "begin":currentDate.value.startTime,
    "end":currentDate.value.endTime,
  }
  const res = await recruitProcessTotal(reqJson)
  listData.value = res
}
</script>

<style scoped lang="less">
.progress-details{
  .top-list-view{
    position: relative;
    width: 100%;
    height: 86px;
    margin-bottom: 22px;
    overflow: hidden;
    .img-bg{
      position: absolute;
      width: auto;
      height: 100%;
      top: 0;
      left: 0;
      z-index: 1;
    }
    .top-list{
      position: absolute;
      width: 100%;
      height: 100%;
      top: 0;
      left: 0;
      z-index: 2;
      display: flex;
      align-items: center;
      padding: 14px 36px;
      .top-li{
        height: 100%;
        display: flex;
        flex-direction: column;
        justify-content: space-between;
        margin-right: 74px;
        .top-li-t1{
          font-size: 16px;
        }
        .top-li-t2{
          font-size: 26px;
          font-weight: 500;
        }
      }
      .top-li-t3{
        font-size: 22px;
        font-weight: 600;
        margin-right: 74px;
      }
    }
  }

  .main-content{
    padding: 16px;
    background-color: #FFFFFF;
    border-radius: 10px;
    .result-wrap {
      display: flex;
      flex-wrap: wrap;
      justify-content: space-between;
      margin-bottom: 10px;
      align-items: center;
      line-height: 30px;
      border-radius: 4px;

      .result-item {
        flex: 1;
        font-size: 12px;
        margin-right: 15px;
        border: 1px solid #ccc;
        padding: 3px 10px;
        border-radius: 4px;
        box-sizing: border-box;
      }

      .result-clear {
        color: #209ee4;
        cursor: pointer;
        font-size: 14px;
        border: 1px solid;
        padding: 1px 5px;
      }
    }
  }
  .search {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 29px;

    .titles {
      color: #333333;

      .title {
        font-size: 20px;
        font-weight: bold;
        margin-right: 12px;
      }

      .update {
        margin-left: 10px;
        color: #209EE4;
        cursor: pointer;

        &:hover {
          text-decoration-line: underline;
        }
      }
    }
  }
}
:deep(::-webkit-scrollbar) {
  width: 8px; /* 滚动条宽度 */
  height: 8px!important; /* 滚动条高度 */
}

:deep(::-webkit-scrollbar-thumb:hover) {
  background-color: #dddddd!important; /* 鼠标悬停时滚动条拇指颜色 */
}

#HrDataList {
  .search{
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 8px;
    .titles {
      color: #333333;

      .title{
        font-size: 20px;
        font-weight: bold;
        margin-right: 12px;
      }
      .update{
        margin-left: 10px;
        color: #209EE4;
        cursor: pointer;
        &:hover{
          text-decoration-line: underline;
        }
      }
    }
    .search-r{
      display: flex;
      .search-input {
        width: 368px;
        height: 32px;
        border-radius: 3px;
        border: 1px solid rgba(179, 192, 200, 0.3);
        color: #B3C0C8;

        ::placeholder {
          color: #B3C0C8;
          font-weight: 400;

        }
        .search-i-i{
          width: 20px;
          height: 20px;
        }
      }
      .tabs{
        padding: 2px;
        background-color: #FFFFFF;
        border-radius: 6px;
        margin-left: 8px;
        display: flex;
        align-items: center;
        .tab-item{
          padding: 4px 10px;
          cursor: pointer;
          margin: 0 5px;
        }
        .tab-item:first-child {
          margin-left: 0;
        }
        .tab-item:last-child {
          margin-right: 0;
        }
        .active {
          color: #209EE4;
          background: #F5F7FB;
          border-radius: 4px 4px 4px 4px;
        }
      }
    }
  }
  .main-content{
    padding: 16px;
    background-color: #FFFFFF;
    border-radius: 10px;
    .filter{
      display: flex;
      flex-wrap: wrap;
      width: 100%;
      .filters-item{
        flex: 0 1 calc((100% - (6 * 17px)) / 7);
        margin-right: 17px;
        margin-bottom: 24px;
        &:nth-of-type(7n) {
          margin-right: 0;
        }
      }
    }
  }
}
:deep(.boxGroup) {
  display: flex;
  flex-direction: column;
}
.bottom_table {
  position: relative;
  background: #ffffff;
  .modify-record{
    height: 31px;
    cursor: pointer;
    display: flex;
    align-items: center;
    .record-text{
      font-size: 14px;
    }
    .record-icon{
      width: 15px;
      height: 15px;
      margin-right: 5px;
    }
  }
  .table_btnC {
    display: flex;
    align-items: baseline;
    position: absolute;
    bottom: -12px;
    left: 0px;
    height: 40px;
  }

  .result-wrap {
    display: flex;
    flex-wrap: wrap;
    justify-content: space-between;
    margin-bottom: 10px;
    align-items: center;
    line-height: 30px;
    border-radius: 4px;

    .result-item {
      flex: 1;
      font-size: 12px;
      margin-right: 15px;
      border: 1px solid #ccc;
      padding: 3px 10px;
      border-radius: 4px;
      box-sizing: border-box;
    }

    .result-clear {
      color: #209ee4;
      cursor: pointer;
      font-size: 14px;
      border: 1px solid;
      padding: 1px 5px;
    }
  }
}
.user-name{
  color: #209EE4;
  cursor: pointer;
  &:hover{
    text-decoration-line: underline;
  }
}
.status-name{
  width: 18px;
  height: 18px;
  border-radius: 3px;
  display: inline-block;
  font-size: 11px;
  text-align: center;
  line-height: 18px;
  margin-right: 5px;

}
.child1{
  color: #FF4242;
  background: rgba(255,66,66,0.1);
}
.child2{
  color: #209EE4;
  background: rgba(32,158,228,0.1);
}
.child3{
  color: #F0A03D;
  background: rgba(240,160,61,0.1);
}
.graduate{
  color: #209EE4;
  border: none;
  background-color: rgba(32,158,228,0.15);
}
.graduate-other{
  color: #F0A03D;
  background-color: rgba(240,160,61,0.15);
  &:hover{
    color: #F0A03D;
  }
}
.interview{
  color: #209EE4;
  background: rgba(32,158,228,0.1);
}
.interview-other{
  color: #16C716;
  background: rgba(22,199,22,0.1);
}
.filter-dropdown {
  padding: 8px;
  min-height: 50px;
  max-height: 300px;
  overflow-x: auto;
  box-sizing: border-box;
  .reset-top{
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 16px;
    .reset-input{
      height: 32px;
      width: 140px;
    }
  }
}

.reset-btn{
  border: 1px solid rgba(179, 192, 200, 0.3)!important
}
</style>
